package com.zhangc.blog.admin.web.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import com.zhangc.blog.base.utils.ResponseUtils;

/**
 * 功能描述:<br>
 * 当访问没有权限的api时候，返回401
 *
 * @author wx:fdzhangc
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
    private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationEntryPoint.class);

    //This method is called whenever an exception is thrown due to an unauthenticated user trying to access a resource that requires authentication.
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e)
            throws IOException, ServletException {
        logger.error("Responding with unauthorized error. Message - {}", e.getMessage());
        if (e instanceof BadCredentialsException) {
            //httpServletResponse.sendError(99, "账号或密码错误");
            ResponseUtils.out(httpServletResponse, "-99", "用户名或密码错误");
            return;
        }
        //httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
        ResponseUtils.out(httpServletResponse, String.valueOf(HttpServletResponse.SC_UNAUTHORIZED), e.getMessage());
    }
}
